package producer

import (
	"gitee.com/jianbiao/go-util/rabbitmqx/config"
	"time"
)

type Option struct {
	manyMsg bool
}

type OptionFunc func(*Option)

//设置多条消息
func WithManyMsg() OptionFunc {
	return func(o *Option) {
		o.manyMsg = true
	}
}

type MqFacade struct {
	manyMsg bool
	producer *producer
	err error
}

func New(cnf *config.Config, queueName string, opts ...OptionFunc) (*MqFacade) {
	polconfig := &poolConfig{
		Addr: cnf.Addr,
		QueueName:queueName,
		Durable :cnf.Durable,
		InitialCap: cnf.ProducerPool.InitialCap,
		MaxIdle:    cnf.ProducerPool.MaxIdle,
		MaxCap:     cnf.ProducerPool.MaxCap,
		IdleTimeout: time.Duration(cnf.ProducerPool.IdleTimeout) * time.Second,
		Confirm:cnf.ProducerPool.Confirm,
	}
	opt := new(Option)
	for _, o := range opts {
		o(opt)
	}
	mqFacade := new(MqFacade)
	mqFacade.manyMsg = opt.manyMsg
	mqFacade.producer, mqFacade.err = newPoll(polconfig)
	return mqFacade
}

//发送消息
func (this *MqFacade) Publish(body string) error {
	if !this.manyMsg{
		defer this.Close()
	}
	if this.err != nil{
		return this.err
	}
	this.err = this.producer.publish(body)
	return this.err
}

//释放资源
func (this *MqFacade) Close() {
	if this.err == nil {
		this.producer.close()
	}
}
